/*
 * Copyright (c) 2021 com.youkeyi. All rights reserved.
 *
 *  @author liuxiawang
 *  @location Shenzhen.China
 *  @date 4/10/21 12:47 AM
 */

package com.youkeyi.ddy.cloud.gateway.swagger;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * SwaggerProvider
 *
 * @Author liuxiawang
 * @Date 2021-03-09 23:39
 * @Location shenzhen.china
 */
@ConfigurationProperties(prefix = "open-api.swagger")
@EnableConfigurationProperties
@Component
@Primary
@Slf4j
public class SwaggerProvider implements SwaggerResourcesProvider {

    @Setter
    @Getter
    private List<String> resources;

    static final String API_URI = "/v3/api-docs";

    public List<SwaggerResource> get() {
        List<SwaggerResource> swaggerResources = new ArrayList<>();
        resources.forEach(s -> {
            String[] split = s.split(",");
            swaggerResources.add(resource(split[0], split[1] + API_URI, split[2]));
        });
        return swaggerResources;
    }

    /**
     * @param name    显示的名字
     * @param oas3Url 文档格式：/manage/product/v3/api-docs(?group=...)
     */
    private SwaggerResource resource(
            String name,
            String oas3Url,
            String swaggerGroup) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        //url: 要看其他微服务是否设置了group 设置了的话
        if (Docket.DEFAULT_GROUP_NAME.equals(swaggerGroup)) {
            swaggerResource.setUrl(oas3Url);
        } else {
            //其他微服务是否设置了group 需要加上"?group=" + 组名
            swaggerResource.setUrl(oas3Url + "?group=" + swaggerGroup);
        }
        swaggerResource.setSwaggerVersion("3.0.3");
        return swaggerResource;
    }
}
